local joystick=class("joystick")

function joystick:init()
	self.working=false
	self.limit=60
	self.stickSize=30
	self.sw,self.sh = love.graphics.getDimensions()
end

function joystick:inBound()
	return love.mouse.getX()< love.graphics.getWidth()/2
end

local function getDist(x,y,z,w)
	return math.sqrt((x-z)*(x-z) + (y-w)*(y-w))
end

function joystick:limitToRound()
	local dist=getDist(self.cx,self.cy,self.sx,self.sy)
	if  dist>self.limit then
		local dx = (self.sx-self.cx)* self.limit/dist
		local dy = (self.sy-self.cy)* self.limit/dist
		self.sx= self.cx+(self.sx-self.cx)* self.limit/dist
		self.sy= self.cy+(self.sy-self.cy)* self.limit/dist
		--self.cx=self.cx+(self.sx-self.cx)* self.limit/dist/10
		--self.cy=self.cy+(self.sy-self.cy)* self.limit/dist/10
	end
end

function joystick:getValue()
	if self.working then 
		self.vx= (self.sx-self.cx)/self.limit
		self.vy= (self.sy-self.cy)/self.limit
	else
		self.vx= 0
		self.vy= 0
	end

end

function joystick:testTouch()
	local touches = love.touch.getTouches()
	self.left = false
	self.right = false
	self.mx,self.my = 0,0
	--touches[1] = love.mouse.isDown(1)
    for i, id in ipairs(touches) do
        local x,y = love.touch.getPosition(id)
        --local x,y = love.mouse.getPosition()
        if x< self.sw/2 then
        	self.left = true
        	self.mx,self.my = x,y
        else
        	self.right = true
        	self.rx,self.ry = x,y
        end
    end
end


function joystick:update()
	self:testTouch()
	if self.working then
		if self.left then
			self.sx,self.sy = self.mx,self.my
			self:limitToRound()
		else
			self.cx=nil
			self.working=false
			return 
		end
	else
		self.working = self.left
		if self.working then	
			self.cx,self.cy = self.mx,self.my
			self.sx,self.sy = self.cx, self.cy
		end
		
	end
	self:getValue()
end


function joystick:control(tank,dt)
	if self.vx ~=0 or self.vy~=0 then
		if math.abs(self.vx)>math.abs(self.vy) then
			if self.vx<0 then
		        tank.dy = 0
		        tank.dx = - tank.speed*dt
		        tank.rot = 3
		    else
		        tank.dy = 0
		        tank.dx = tank.speed*dt
		        tank.rot = 1
		    end
		else
			if self.vy<0 then
		        tank.dx = 0
		        tank.dy = - tank.speed*dt
		        tank.rot = 0
		    else
		        tank.dx = 0
		        tank.dy = tank.speed*dt
		        tank.rot = 2
		    end
		end
	end

    if self.right then
    	tank:fire()
    end
end


function joystick:draw()
	if self.working then
		love.graphics.setColor(1, 1, 1, 1)
		love.graphics.circle("line", self.cx, self.cy, self.limit)
		love.graphics.setColor(0.5, 0.5,0.5, 1)
		love.graphics.circle("fill", self.sx, self.sy, self.stickSize)
	end

	if self.right then
		love.graphics.setColor(0.5, 0.5,0.5, 1)
		love.graphics.circle("fill", self.rx, self.ry, self.stickSize)
	end
	--love.graphics.print(string.format("axis x: %0.2f; axis y: %0.2f",self.vx,self.vy),100,100)
end

return joystick